/*
Simple Forum Auto Poster.
Copyright (C) 2011 Gianni Van Hoecke.

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
package domain.cipher;

import domain.DomainController;
import java.io.Serializable;
import java.util.logging.Level;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

/**
 *
 * @author Gianni Van Hoecke <gianni.vh@gmail.com>
 * Creates a security key.
 *
 * Remember that an instance of this class cannot be used with another instance.
 * You'll need to store the object of this class for later decryption.
 */
public class CipherManager implements Serializable
{
    private static final char[] pw_const = new char[]{'@', 'S', 'F', 'a', 'P', '#', '0', '.', '1'};
    transient private Cipher desCipher;
    transient private DESKeySpec desKeySpec;
    transient private SecretKeyFactory keyFactory;
    private SecretKey secretKey;

    /**
     * Default constructor. Initializes the Cipher module.
     * The Cipher mode is by default Cipher.ENCRYPT_MODE and usable without calling the setMode method.
     */
    public CipherManager()
    {
        try
        {
            //Create the key...
            byte[] key = pw_const.toString().getBytes();
            desKeySpec = new DESKeySpec(key);
            keyFactory = SecretKeyFactory.getInstance("DES");
            secretKey = keyFactory.generateSecret(desKeySpec);

            //Create the cipher...
            desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
            desCipher.init(Cipher.ENCRYPT_MODE, secretKey);
        }
        catch(Exception ex)
        {
            DomainController.getInstance().getLogger().log(Level.SEVERE, "Could not create key: {0}", ex.getMessage());
        }
    }

    /**
     * @param mode The Cipher mode Cipher.ENCRYPT_MODE or Cipher.DECRYPT_MODE
     */
    public void setMode(int mode)
    {
        try
        {
            desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
            desCipher.init(mode, secretKey);
        }
        catch(Exception ex)
        {
            DomainController.getInstance().getLogger().log(Level.SEVERE, "Could not create key: {0}", ex.getMessage());
        }
    }

    /**
     * @return The Cipher object needed to encrypt and decrypt.
     */
    public Cipher getDesCipher()
    {
        return desCipher;
    }
}